package com.tenglong.teacher.ui.adapter.viewholder.homework;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.cuotibao.zhuoxiao.basics.GlobalConstant;
import com.cuotibao.zhuoxiao.basics.utils.ToastUtils;
import com.cuotibao.zhuoxiao.basics.utils.glide.GlideOptions;
import com.netease.nim.uikit.common.util.sys.TimeUtil;
import com.tenglong.teacher.R;
import com.tenglong.teacher.data.resultInfo.base.BaseResult;
import com.tenglong.teacher.data.resultInfo.base.ResultVerifier;
import com.tenglong.teacher.data.resultInfo.homework.HomeWork;
import com.tenglong.teacher.data.resultInfo.homework.HomeWorkPublishInfo;
import com.tenglong.teacher.services.hdx.CreateRequestEntity;
import com.tenglong.teacher.ui.PhotoBrowserActivity;
import com.tenglong.teacher.ui.adapter.HomeworkStudentListAdapter;
import com.tenglong.teacher.ui.adapter.viewholder.base.BaseViewHolder;
import com.tenglong.teacher.ui.audio.MediaManager;
import com.tenglong.teacher.ui.dialog.ExitDialog;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * @author hdx on 2019/3/13.
 */
public class StudentPublishViewHolder extends BaseViewHolder<HomeWork> implements View.OnClickListener {
    private TextView homeworkContent, tvHomeworkAudio;
    private ViewGroup imageGroup, homeworkAudio;
    private HomeWorkPublishInfo data;
    private Context mContext;
    private TextView btnAbort;
    private HomeworkStudentListAdapter.HomeworkStudentListListener listListener;
    private ImageView ivHomeworkAudio;

    public StudentPublishViewHolder(View itemView) {
        super(itemView);
        this.mContext = itemView.getContext();
        initView();
        setListeners();
    }

    public StudentPublishViewHolder(View itemView, HomeworkStudentListAdapter.HomeworkStudentListListener listListener) {
        this(itemView);
        this.listListener = listListener;
    }

    private void setListeners() {
        homeworkAudio.setOnClickListener(this);
        for (int i = 0; i < imageGroup.getChildCount(); i++) {
            View childView = imageGroup.getChildAt(i);
            childView.setOnClickListener(this);
        }
        btnAbort.setOnClickListener(this);
    }

    private void initView() {
        homeworkContent = itemView.findViewById(R.id.homeworkContent);
        homeworkAudio = itemView.findViewById(R.id.homeworkAudio);
        imageGroup = itemView.findViewById(R.id.imageGroup);
        btnAbort = itemView.findViewById(R.id.btnAbort);
        ivHomeworkAudio = itemView.findViewById(R.id.iv_homeworkAudio);
        tvHomeworkAudio = itemView.findViewById(R.id.tv_homeworkAudio);
    }

    @Override
    public void setLayoutInfo(HomeWork info) {
        this.data = (HomeWorkPublishInfo) info;
        homeworkContent.setVisibility(TextUtils.isEmpty(data.homeworkContent) ? View.GONE : View.VISIBLE);
        if (homeworkContent.getVisibility() == View.VISIBLE) {
            homeworkContent.setText(data.homeworkContent);
        }
        homeworkAudio.setVisibility(TextUtils.isEmpty(data.homeworkAudioUrl) ? View.GONE : View.VISIBLE);
        if (homeworkAudio.getVisibility() == View.VISIBLE) {
            long seconds = TimeUtil.getSecondsByMilliseconds(data.homeworkAudioDuration);
            if (seconds >= 0) {
                tvHomeworkAudio.setText(seconds + "\"");
            } else {
                tvHomeworkAudio.setText("");
            }
        }
        RequestOptions options = GlideOptions.getGlideRequestOptions().
                error(com.netease.nim.uikit.R.drawable.nim_image_default).
                placeholder(com.netease.nim.uikit.R.drawable.nim_image_default);
        for (int i = 0; i < imageGroup.getChildCount(); i++) {
            ImageView childView = (ImageView) imageGroup.getChildAt(i);
            if (data.homeworkImageUrls.size() > i) {
                childView.setVisibility(View.VISIBLE);
                String imageUrl = data.homeworkImageUrls.get(i);
                Glide.with(mContext)
                        .load(imageUrl)
                        .apply(options)
                        .into((ImageView) imageGroup.getChildAt(i));
            } else {
                childView.setBackground(null);
                childView.setVisibility(View.GONE);
            }
        }
        setAbortState();
    }

    private void setAbortState() {
        btnAbort.setText(data.isHoomworkAbort ? "已截止" : "截止");
        btnAbort.setEnabled(!data.isHoomworkAbort);
        btnAbort.setClickable(!data.isHoomworkAbort);
        btnAbort.setSelected(!data.isHoomworkAbort);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.homeworkAudio:
                if (!TextUtils.isEmpty(data.homeworkAudioUrl)) {
                    MediaManager.release();
                    MediaManager.playSound(data.homeworkAudioUrl, null);
                }
                break;
            case R.id.image1:
            case R.id.image2:
            case R.id.image3:
            case R.id.image4:
            case R.id.image5:
            case R.id.image6:
            case R.id.image7:
            case R.id.image8:
                if (data.homeworkImageUrls != null && data.homeworkImageUrls.size() > 0) {
                    int index = imageGroup.indexOfChild(v);
                    Intent i = new Intent();
                    i.setClass(mContext, PhotoBrowserActivity.class);
                    i.putExtra(GlobalConstant.KEY_IMAGE_URLS, data.homeworkImageUrls.toArray(new String[data.homeworkImageUrls.size()]));
                    i.putExtra(GlobalConstant.KEY_CURRENT_IMAGE_URL, data.homeworkImageUrls.get(index));
                    mContext.startActivity(i);
                    ((Activity) mContext).overridePendingTransition(0, 0);
                }
                break;
            case R.id.btnAbort:
                int notSubmitNumber = 0;
                if (listListener != null) {
                    notSubmitNumber = listListener.getNotSubmitStudentNumber();
                }
                ExitDialog.getExitDialog(notSubmitNumber == 0 ? "您确定要截止此次作业?" : ((notSubmitNumber == -1) ? "还没有学生提交作业，是否截止?"
                        : "还有 " + notSubmitNumber + " 名学生未提交作业，是否截止?")).setExitListener(new ExitDialog.ExitListener() {
                    @Override
                    public void onExit(boolean exitState) {
                        if (exitState) {
                            abortHomework();
                        }
                    }
                }).show(((FragmentActivity) mContext).getSupportFragmentManager(), "dialog");
                break;
        }
    }

    private void abortHomework() {
        CreateRequestEntity.getWebService().homeworkStop(data.sessionId).enqueue(new Callback<BaseResult<Boolean>>() {
            @Override
            public void onResponse(Call<BaseResult<Boolean>> call, Response<BaseResult<Boolean>> response) {
                if (ResultVerifier.isSucceed(response)) {
                    data.isHoomworkAbort = response.body().data;
                    setAbortState();
                    ((Activity) mContext).setResult(Activity.RESULT_OK);
                } else {
                    ToastUtils.showCenterToast(ResultVerifier.serceErrers(response));
                }
            }

            @Override
            public void onFailure(Call<BaseResult<Boolean>> call, Throwable t) {
                ResultVerifier.systerErrers(t);
            }
        });
    }
}
